<template>
    <div class="dispose-message-factory">
        <!-- 外层只做滚动容器，不再用 v-show 切 -->
        <div class="chat-content scrollbar-container" ref="scrollbarContainer">
            <!-- 1️⃣ 私聊消息 -->
            <div class="friend-chat-list" ref="listRef" v-if="props.chatMessageType === 'userChat'">
                <template v-if="messages && messages.length">
                    <template v-for="(group, index) in groupedMessages" :key="index">
                        <!-- 显示时间分组 -->
                        <div class="time-group" v-if="group.messages.length">
                            <span class="time-label">{{ group.timeLabel }}</span>
                        </div>
                        <!-- 显示分组内的消息 -->
                        <div v-for="msg in group.messages" :key="msg.id"
                            :class="['msg', msg.from === userStore().userInfo.uu_id ? 'self' : 'other']">
                            <!-- 左侧：对方头像（其他人） -->
                            <div v-if="msg.from !== userStore().userInfo.uu_id" class="avatar">
                                <n-popover placement="right" trigger="click" :overlap="leftPopoVisible">
                                    <template #trigger>
                                        <n-avatar size="medium"
                                            :src="msg.avatar ?? msg.userNickAvatar ?? targetChatFriend.avatar"
                                            :fallback-src="DefaultAvatar" @click="friendItemUUID = msg.from" />
                                    </template>
                                    <!-- 展示基本信息 -->
                                    <div class="show-user-info-popoer">
                                        <div id="user-popover-info">
                                            <div id="basic-info" class="flex items-center justify-evenly">
                                                <n-avatar :src="selectedFriend?.friendDetails.avatar" size="large"
                                                    style="width: 50px;height: 50px;" />
                                                <div id="other-info">
                                                    <div id="info-wrapper-one" class="flex items-center justify-around">
                                                        <span>{{ selectedFriend?.remark ||
                                                            selectedFriend?.friendDetails.username }}</span>
                                                        <img :src="getGenderIcon(selectedFriend?.friendDetails.gex!)"
                                                            alt="">
                                                        <n-popover trigger="click" :overlap="moreOverlapVisible"
                                                            placement="right">
                                                            <template #trigger><el-icon size="15">
                                                                    <MoreFilled />
                                                                </el-icon></template>
                                                            <!-- 设置二级popover -->
                                                            <div id="chat-user-popover-second-menus">
                                                                <div id="second-menu-items"
                                                                    v-for="(secondItem, secondItemIndex) in chatPopoverSecondMenus"
                                                                    :key="secondItemIndex"
                                                                    @click="popoverMenuClick(secondItem.key)">
                                                                    <span :style="{
                                                                        color: secondItem.key === 'delete-friend' ? 'red' : 'black',
                                                                        fontSize: secondItem.key === 'delete-friend' ? '15px' : '14px',
                                                                        height: secondItem.key === 'delete-friend' ? '30px' : '40px'
                                                                    }">{{ secondItem.label }}</span>
                                                                </div>
                                                            </div>
                                                        </n-popover>
                                                    </div>
                                                    <span>昵称:&ensp;&ensp;{{ selectedFriend?.friendDetails.username
                                                        }}</span>
                                                    <span>Id: &ensp;&ensp;{{ selectedFriend?.friendDetails.uu_id
                                                        }}</span>
                                                    <span>地区:&ensp;&ensp;{{ selectedFriend?.friendDetails.area || "未知地域"
                                                        }}</span>
                                                </div>
                                            </div>
                                            <!-- 备注和分组信息 -->
                                            <div id="special-info">
                                                <div id="remark-info">
                                                    <label for="remark">
                                                        <span>备注:&ensp;&ensp;</span>
                                                    </label>
                                                    <span id="remark" v-show="!showSetChangeInfoStatus.remark"
                                                        @click="showSetChangeInfoStatus.remark = !showSetChangeInfoStatus.remark">{{
                                                            selectedFriend?.remark || "设置备注"
                                                        }}</span>
                                                    <input type="text" v-model="changeFriendInfo.remark"
                                                        v-show="showSetChangeInfoStatus.remark"
                                                        @blur="handleChangeBlur('input-blur')">
                                                    <!-- <n-input v-model:value="changeFriendInfo.remark"
                                                v-show="showSetChangeInfoStatus.remark" clearable :minlength1="1"
                                                :maxlength="10" /> -->
                                                </div>
                                                <div id="group-info">
                                                    <label for="group">
                                                        <span id="group">分组:&ensp;&ensp;</span>
                                                    </label>
                                                    <span v-show="!showSetChangeInfoStatus.group"
                                                        @click="showSetChangeInfoStatus.group = !showSetChangeInfoStatus.group">{{
                                                            selectedFriend?.group || "设置分组"
                                                        }}</span>
                                                    <n-select v-show="showSetChangeInfoStatus.group" size="small"
                                                        v-model:value="changeFriendInfo.group"
                                                        :options="props.groupMenus" clearable
                                                        @blur="handleChangeBlur('select-blur')" style="height: 20px;"
                                                        :placeholder="props.groupMenus[0].label" />
                                                </div>
                                                <div id="circle-of-friends" @click="ElMessage.error('去看ta的朋友圈')">
                                                    <span>去看ta的朋友圈</span>
                                                    <el-icon size="20">
                                                        <ArrowRight />
                                                    </el-icon>
                                                </div>
                                            </div>
                                            <!-- 聊天按钮 -->
                                            <div id="chat-btns">
                                                <div id="voice-chat" @click="handleChatBtnsInPopover('voice-chat')">
                                                    <span>语音聊天</span>
                                                    <img src="https://img.icons8.com/?size=100&id=CCDYqb5KK5vI&format=png&color=000000   "
                                                        alt="">
                                                </div>
                                                <div id="video-chat" @click="handleChatBtnsInPopover('video-chat')">
                                                    <span>视频聊天</span>
                                                    <img src="https://img.icons8.com/?size=100&id=118635&format=png&color=000000"
                                                        alt="">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </n-popover>
                            </div>

                            <!-- 中间：气泡 -->
                            <div :class="[
                                'bubble',
                                msg.from === userStore().userInfo.uu_id ? 'bubble-self' : 'bubble-other'
                            ]">
                                <!-- 文件消息 -->
                                <!-- <FileCard v-if="isFileMessage(msg.message)" :file-info="JSON.parse(msg.message)" /> -->
                                <FileCard v-if="msg.type === MsgType.FILE" :file-info="JSON.parse(msg.message)" />

                                <!-- 文本消息 -->
                                <div v-else-if="msg.type === MsgType.TEXT" class="text-container">
                                    <!-- 图片元素       测试的时候不渲染这个了，后期考虑删除这个 -->
                                    <!-- <span v-if="msg.from !== userStore().userInfo.uu_id" class="bubble-image other">
                                        <img :src="getRandomRIGImage()" alt="Other Image" />
                                    </span>
                                    <span v-else class="bubble-image self">
                                        <img :src="getRandomRIGImage()" alt="Self Image" />
                                    </span> -->

                                    <!-- 文本内容 -->
                                    <span class="text">{{ msg.message }}</span>
                                </div>
                            </div>

                            <!-- 右侧：当前用户头像 -->
                            <div v-if="msg.from === userStore().userInfo.uu_id" class="avatar">
                                <n-avatar size="medium" :src="userStore().userInfo.avatar"
                                    :fallback-src="DefaultAvatar" />
                            </div>
                        </div>
                    </template>
                </template>
                <n-empty v-else description="暂无聊天内容哦~" />
            </div>

            <!-- 2️⃣ 群聊消息 -->
            <div class="group-chat-content" v-else-if="props.chatMessageType === 'groupChat'">
                <!-- 消息列表 -->
                <template v-if="groupedGroupMessages && groupedGroupMessages.length">
                    <template v-for="(group, index) in groupedGroupMessages" :key="index">
                        <!-- 显示时间分组 -->
                        <div class="time-group" v-if="group.messages.length">
                            <span class="time-label">{{ group.timeLabel }}</span>
                        </div>

                        <!-- 显示分组内的消息 -->
                        <div v-for="msg in group.messages" :key="msg.id">
                            <!-- 如果是拉取群成员消息，则全局显示 -->
                            <div v-if="msg.type === MsgType.GroupInvation" class="group-invation-message">
                                <span> {{ msg.message }}</span><br>
                                <span>与这些群友还不是好友<n-tag :bordered="false" type="info" v-for="friend in msg.invationList"
                                        :key="friend.key"
                                        style="min-width: 50px;max-width: 70px;margin-left: 5px;overflow: hidden;background-color: transparent;">{{
                                            friend.label
                                        }}</n-tag></span>
                            </div>
                            <div v-else :class="['msg', msg.from === userStore().userInfo.uu_id ? 'self' : 'other']">
                                <!-- 头像：自己放右边，别人放左边 -->
                                <!-- 对方头像 -->
                                <n-popover v-if="msg.from !== userStore().userInfo.uu_id" trigger="click"
                                    placement="right">
                                    <template #trigger>
                                        <n-avatar class="avatar" size="small" :src="msg.userNickAvatar"
                                            :fallback-src="DefaultAvatar" />
                                    </template>
                                    <!-- 显示群成员的基本信息，也可以通过点击这里的临时聊天按钮建立临时聊天、当然聊天内容不会保存 -->
                                    <div class="group-members-info" v-show="!temporaryConversationStatus">
                                        <figure class="flex">
                                            <n-avatar :src="msg.userNickAvatar" size="large" />
                                            <div id="show-members-basic-info" class="flex flex-col"
                                                style="margin-left: 5px;">
                                                <figcaption>
                                                    <label for="uuId"><span>uuId:</span></label>
                                                    <span id="uuId">{{ msg.from }}</span>
                                                </figcaption>
                                                <figcaption>
                                                    <label for="nickname"><span>用户名:</span></label>
                                                    <span id="nickname">{{ msg.userNickName }}</span>
                                                </figcaption>
                                            </div>
                                        </figure>
                                        <!-- 这里是功能按钮了（加好友、创建临时聊天） -->
                                        <div id="members-dispose-btns">
                                            <div id="add-friend-btns"
                                                @click="showAddFriendPrompt(props.connectedWebsocket, msg)">
                                                <label for="add-friend"><span>加好友</span></label>
                                                <img src="https://img.icons8.com/?size=100&id=117342&format=png&color=000000"
                                                    alt="" id="add-friend">
                                            </div>
                                            <div id="temporary-conversations-btns"
                                                @click="temporaryConversationStatus = !temporaryConversationStatus">
                                                <label for="temporary"><span>临时会话</span></label>
                                                <img src="https://img.icons8.com/?size=100&id=M833L1eYJ2xf&format=png&color=000000"
                                                    alt="" id="temporary">
                                            </div>
                                        </div>
                                    </div>
                                    <!-- 展示临时会话窗口 -->
                                    <div class="group-members-temporary-conversation"
                                        v-show="temporaryConversationStatus">
                                        <!-- 头部信息（返回按钮、用户名） -->
                                        <div id="group-members-tempory-conversation-header-infos">

                                            <head>hedaer-info</head>
                                        </div>
                                    </div>
                                </n-popover>
                                <!-- 当前用户头像 -->
                                <n-avatar v-else class="avatar" size="small" :src="userStore().userInfo.avatar" />

                                <!-- 气泡：自己右对齐，别人左对齐 -->
                                <div :class="[
                                    'bubble',
                                    msg.from === userStore().userInfo.uu_id ? 'bubble-self' : 'bubble-other',
                                ]">
                                    <!-- 如果是文件消息 -->
                                    <!-- <FileCard v-if="isFileMessage(msg.message)" :file-info="JSON.parse(msg.message)" /> -->
                                    <FileCard v-if="msg.type === MsgType.FILE" :file-info="JSON.parse(msg.message)" />
                                    <!-- 如果是文本消息 -->
                                    <div class="text-container" v-else-if="msg.type === MsgType.TEXT">
                                        <!-- 图片元素    测试的时候不使用这个，避免不必要的消耗    -->
                                        <!-- <span v-if="msg.from !== userStore().userInfo.uu_id" class="bubble-image other">
                                            <img :src="getRandomRIGImage()" alt="Other Image" />
                                        </span>
                                        <span v-else class="bubble-image self">
                                            <img :src="getRandomRIGImage()" alt="Self Image" />
                                        </span> -->
                                        <span class="text">{{ msg.message }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>
                </template>

                <!-- 空状态 -->
                <n-empty v-else description="群聊信息为空！" />
            </div>
        </div>
    </div>

</template>



<script setup lang="ts">
import { useFactory } from '@/utils/factory';
import { chatStore } from '@/store/chatStore';
import { friendStore } from '@/store/friendStore';
import { FactoryResult, FriendMenuList, GroupMessage, MsgType, UserFriendInfo } from '@/types/types';
import { targetChatFriend, targetChatGroup } from '@/utils/socketPageService';
import { computed, nextTick, onMounted, PropType, reactive, ref, watch } from 'vue';
import { userStore } from '@/store/userStore';
import DefaultAvatar from "@images/default/avatar.jpeg"
import FileCard from "@/factories/File/FileCard.vue"
import { ElMessage } from 'element-plus';
import BoyImage from "@images/Chat/boy.svg"
import GirlImage from "@images/Chat/girl.svg"
import UnknownGender from "@images/Chat/unknown.svg"
import { showAddFriendPrompt } from '@/utils/contextMenu';

const props = defineProps({
    chatMessageType: {
        type: String,
        required: true
    },
    groupMenus: {
        type: Array as PropType<FriendMenuList[]>,
        required: true
    },
    connectedWebsocket: {
        type: Object as PropType<WebSocket>,
        required: true
    }
})

const emits = defineEmits(['send-changeFriend-info']);

let factory: FactoryResult = reactive({
    user_store: null,
    friend_store: null,
    chat_store: null
})

const user_store = userStore();
const friend_store = friendStore();
const chat_store = chatStore();


// 显示popover的变量
const leftPopoVisible = ref<boolean>(false);
const rightPopoVisible = ref<boolean>(false);


// 获取性别图标
function getGenderIcon(gender: string) {
    switch (gender) {
        case 'boy':
            return BoyImage;
        case 'girl':
            return GirlImage;
        case '未知':
            return UnknownGender;
    }
}


/* 实时消息列表（已排序） */
const messages = computed(() => chatStore().getPrivateMessages(targetChatFriend.uu_id));


// 实时群聊消息
const groupMessages = computed(() => chatStore().getGroupMessages(targetChatGroup.group_id));


// 根据时间戳分组消息       私聊
const groupedMessages = computed(() => {
    const groups: any[] = [];
    let currentGroup: any = null;

    // 先对 messages.value 按时间戳排序
    const sortedMessages = messages.value.sort((a, b) => {
        return new Date(a.timeStamp).getTime() - new Date(b.timeStamp).getTime();
    });

    sortedMessages.forEach((msg) => {
        const msgTime = new Date(msg.timeStamp);
        const msgMinute = msgTime.getMinutes();
        const msgHour = msgTime.getHours();

        // 如果当前分组不存在或时间不匹配，则创建新分组
        if (!currentGroup || currentGroup.hour !== msgHour || currentGroup.minute !== msgMinute) {
            currentGroup = {
                timeLabel: `${msgHour.toString().padStart(2, '0')}:${msgMinute.toString().padStart(2, '0')}`,
                hour: msgHour,
                minute: msgMinute,
                messages: [],
            };
            groups.push(currentGroup);
        }

        // 将消息添加到当前分组
        currentGroup.messages.push(msg);
    });

    return groups;
});

// 根据时间戳分组消息       群聊
const groupedGroupMessages = computed(() => {
    const groups: any[] = [];
    let currentGroup: any = null;

    groupMessages.value.forEach((msg) => {
        // 将字符串时间戳转换为 Date 对象
        const msgTime = new Date(msg.timeStamp); // 假设时间戳是字符串格式
        const msgHour = msgTime.getHours();
        const msgMinute = msgTime.getMinutes();

        // 如果当前分组不存在或时间不匹配，则创建新分组
        if (!currentGroup || currentGroup.hour !== msgHour || currentGroup.minute !== msgMinute) {
            currentGroup = {
                timeLabel: `${msgHour.toString().padStart(2, '0')}:${msgMinute.toString().padStart(2, '0')}`,
                hour: msgHour,
                minute: msgMinute,
                messages: [],
            };
            groups.push(currentGroup);
        }

        // 将消息添加到当前分组
        currentGroup.messages.push(msg);
    });

    return groups;
});


// 获取随机GIF图片的事件
function getRandomRIGImage() {
    const images = [
        "https://i.imgs.ovh/2025/07/26/nC6OX.gif", "https://i.imgs.ovh/2025/07/26/nCqpU.gif",
        "https://i.imgs.ovh/2025/07/26/nCgrN.gif", "https://i.imgs.ovh/2025/07/26/nCAxA.gif", "https://i.imgs.ovh/2025/07/26/nCzW4.gif",
        "https://i.imgs.ovh/2025/07/26/nCbVC.gif", "https://i.imgs.ovh/2025/07/26/nCUNq.gif", "https://i.imgs.ovh/2025/07/26/nCTot.gif",
        "https://i.imgs.ovh/2025/07/26/nCLka.gif", "https://i.imgs.ovh/2025/07/26/nCSOe.gif"
    ];
    const randomIndex = Math.floor(Math.random() * images.length);
    return images[randomIndex];
}

const friendItemUUID = ref<string>("");
const selectedFriend = computed((): UserFriendInfo | undefined => friend_store.getFriendListFromUserId(friendItemUUID.value));

// 判断是不是文件消息
function isFileMessage(content: string) {
    try {
        const obj = JSON.parse(content);
        return obj && typeof obj === 'object' && 'fileKey' in obj;
    } catch {
        return false;
    }
}


// input、select失焦处理事件
function handleChangeBlur(type: string) {
    // 定义消息类型和内容的映射                 这是修改之后的函数，确保了类型安全，修改之前的函数三行完成（两个三元运算，一个emits）
    const typeMap = {
        'input-blur': {
            infoType: 'friend-remark',
            infoContent: changeFriendInfo.remark,
        },
        'select-blur': {
            infoType: 'friend-group',
            infoContent: changeFriendInfo.group,
        },
    };

    // 获取当前类型的消息类型和内容
    const { infoType, infoContent } = typeMap[type as keyof typeof typeMap] || {};

    // 如果类型不匹配，显示错误信息并返回
    if (!infoType || infoContent === undefined) {
        console.error(`未知的类型: ${type}`);
        return;
    }

    ElMessage.warning("市区了！");

    // 发送事件
    emits('send-changeFriend-info', infoType, infoContent, changeFriendInfo);
}

// 存储修改用户备注、分组信息的对象
const changeFriendInfo = reactive({
    friendId: targetChatFriend.uu_id,       // 这个emmm有点多余
    remark: null,
    group: null
})
// 控制设置信息信息状态
const showSetChangeInfoStatus = reactive({
    remark: ref<boolean>(false),
    group: ref<boolean>(false)
})


const moreOverlapVisible = ref<boolean>(false);
// 二级菜单列表
const chatPopoverSecondMenus = reactive([
    { label: "设置备注", key: "set-remark" },
    { label: "设置分组", key: "set-group" },
    { label: "删除好友", key: "delete-friend" }
]);
// 处理菜单事件
function popoverMenuClick(key: string) {
    const actions = {
        'set-remark': () => {
            showSetChangeInfoStatus.remark = true;
            showSetChangeInfoStatus.group = false;
        },
        'set-group': () => {
            showSetChangeInfoStatus.remark = false;
            showSetChangeInfoStatus.group = true;
        },
        'delete-friend': () => {
            ElMessage.error("删除好友！");
        }
    };
    const action = actions[key as keyof typeof actions];
    if (action) {
        action();
    } else {
        console.warn(`未知操作: ${key}`);
    }
}

// 控制着展示临时聊天信息的区域
const temporaryConversationStatus = ref<boolean>(false);


// 滚动条监听元素
const scrollbarContainer = ref<HTMLElement | null>(null);
// 1. 精准滚动到底部
function scrollToBottom() {
    nextTick(() => {
        if (scrollbarContainer.value) {
            scrollbarContainer.value.scrollTo({
                top: scrollbarContainer.value.scrollHeight,
                behavior: 'smooth',
            });
        }
    });
}
// 2. 监听
watch([messages, groupMessages], ([newMessageLength, oldMessageLength], [newGroupMessageLength, oldGroupMessageLength]) => {
    if (newMessageLength || newGroupMessageLength) {
        scrollToBottom();
    }
    scrollToBottom();
}, { deep: true });


// 处理popover中的chat-btns事件
function handleChatBtnsInPopover(type: string) {
    ElMessage.success(type);
}



onMounted(async (): Promise<void> => {
    // let factory = await useFactory();
    // factory.user_store = factory.user_store;
    // factory.friend_store = factory.friend_store;
    // factory.chat_store = factory.chat_store;
})

</script>


<style scoped lang="scss">
@import url("./dispose-message.scss");

.show-user-info-popoer {
    #user-popover-info {
        width: 240px;
        height: 300px;

        #basic-info {
            height: 130px;
            color: black;
            border-bottom: 1px solid darkgray;


            #other-info {
                width: 170px;
                font-size: 14px;
                display: flex;
                flex-direction: column;

                img {
                    width: 15px;
                    height: 20px;
                }

                #info-wrapper-one {
                    // border: 1px solid red;
                }
            }
        }

        #special-info {
            height: 100px;
            border-bottom: 1px solid darkgray;

            div {
                font-size: 13px;
                display: flex;
                align-items: center;
                justify-content: center;
                height: 33.3%;
            }

            #circle-of-friends {
                // background-color: red;
            }

            .n-input,
            .n-select {
                // height: 55%;
                width: 170px;
            }

            input {
                width: 150px;
                border: 2px solid white;
                border-radius: 5px;
                outline: none;
                transition: border-color 0.3s;

                &:focus {
                    border-color: #00cc00;
                }
            }
        }

        #chat-btns {
            display: flex;
            align-items: center;
            justify-content: space-evenly;

            #voice-chat,
            #video-chat {
                font-size: 13px;
                color: #00cc00;
                display: flex;
                flex-direction: column;
                align-items: center;

                img {
                    width: 50px;
                    height: 50px;
                }

            }
        }
    }
}

#chat-user-popover-second-menus {
    width: 100px;

    #second-menu-items {
        transition: background-color 0.3s ease-in-out;
        width: 100%;
        font-size: 14px;
        margin: 3px;
        cursor: pointer;
        text-align: center;

        &:hover {
            background-color: rgba(0, 0, 0, 0.1);
        }
    }
}
</style>